#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <pthread.h>

using namespace std;

struct ThreadData
{
    int sockfd;
    struct sockaddr_in sk;
};

void User(const string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);

    while (true)
    {
        printf("Plase Enter#");
        string send;
        getline(cin, send);
        sendto(td->sockfd, send.c_str(), send.size(), 0, (struct sockaddr *)&td->sk, sizeof(td->sk));
    }
}

void *recv_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);

    while (true)
    {
        // 接收服务器返回的消息
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        recvfrom(td->sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        cerr << buffer << endl;
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        User(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct ThreadData td;
    bzero(&td, sizeof(td));
    td.sk.sin_family = AF_INET;
    td.sk.sin_port = htons(serverport); //?
    td.sk.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(td.sk);

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }

    // 当我们首次发送消息时，系统会为我们自动bind

    while (true)
    {
        pthread_t recv, send;
        pthread_create(&recv, nullptr, recv_message, &td);
        pthread_create(&send, nullptr, send_message, &td);

        pthread_join(recv, nullptr);
        pthread_join(send, nullptr);
    }

    close(td.sockfd);
    return 0;
}